﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    manager = new QNetworkAccessManager(this);
    QMetaObject::Connection connRet = QObject::connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
    Q_ASSERT(connRet);
    SendRequest("http://210.45.147.188:8080/reader/redr_verify.php");
    ui->tabWidget->setCurrentIndex(0);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::requestFinished(QNetworkReply *reply)
{
    qDebug()<<reply->url();

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if(statusCode.isValid())
        qDebug() << "status code=" << statusCode.toInt();

    QVariant reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
    if(reason.isValid())
        qDebug() << "reason=" << reason.toString();

    QNetworkReply::NetworkError err = reply->error();
    if(err != QNetworkReply::NoError)
        qDebug() << "Failed: " << reply->errorString();
    else {
        if(reply->url() == QUrl("http://210.45.147.188:8080/reader/redr_verify.php")){
            QString ret = reply->readAll();
            if(first){
                first = false;
                csrf = GetSubString(ret,"name=\"csrf_token\" value=\"(.*)\" />");
                qDebug()<<csrf;
                SendRequest("http://210.45.147.188:8080/reader/captcha.php");
            }else {
                if(statusCode.toInt() == 302){
                    SendRequest("http://210.45.147.188:8080/reader/redr_info.php");
                }else{
                    ui->label_2->setText(GetSubString(ret,"color=\"red\">(.*)</font>"));
                }
            }
        }else if(reply->url() == QUrl("http://210.45.147.188:8080/reader/captcha.php")){
            QPixmap img;
            img.loadFromData(reply->readAll());
            ui->label->setPixmap(img);
        }else if(reply->url() == QUrl("http://210.45.147.188:8080/reader/redr_info.php")){
            QString ret = reply->readAll();
            name = GetSubString(ret,"<span class=\"profile-name\">(.*)</span> </div>\r\n");
            ui->label_2->setText(name);
            SendRequest("http://210.45.147.188:8080/reader/book_lst.php");
        }else if(reply->url() == QUrl("http://210.45.147.188:8080/reader/book_lst.php")){
            QString ret = reply->readAll();
            QStringList id = GetSubStringEX(ret,"<td class=\"whitetext\" width=\"10%\">(.*)</td>");
            QStringList time = GetSubStringEX(ret,"<td class=\"whitetext\" width=\"13%\">(.*)</td>");
            QStringList book = GetSubStringEX(ret,"marc_no=(.*)</td>");
            books.clear();
            for (int i=0;i<id.length();++i) {
                Book tmp;
                tmp.id = id[i];
                tmp.time_begin = time[i*2];
                tmp.time_end = time[2*i+1];
                tmp.time_end.replace("<font color=>","").replace("        </font>","");
                QStringList data = book[i].split("\">");
                tmp.url = data[0];
                data = data[1].split("</a> / ");
                tmp.name = Unescape(data[0]);
                tmp.author = Unescape(data[1]);
                books.append(tmp);
                qDebug()<<tmp.id<<tmp.time_begin<<tmp.time_end<<tmp.name<<tmp.author<<tmp.url;
            }
            RefreshBooksDisplay();
            ui->tabWidget->setCurrentIndex(1);
        }
    }
}

QString MainWindow::GetSubString(QString src, QString pattern)
{
    return GetSubStringEX(src,pattern)[0];
}

QStringList MainWindow::GetSubStringEX(QString src, QString pattern)
{
    QStringList ret;
    QRegExp rx(pattern);
    rx.setMinimal(true);
    int pos = 0;
    while((pos = rx.indexIn(src,pos)) != -1){
        ret<<rx.capturedTexts()[1];
        pos+=rx.matchedLength();
    }
    return ret;
}

QString MainWindow::Unescape(QString src)
{
    QTextDocument doc;
    doc.setHtml(src);
    return doc.toPlainText();
}

void MainWindow::SendRequest(QString url, QString data)
{
    QNetworkRequest req((QUrl(url)));
    if(data!=""){
        req.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/x-www-form-urlencoded"));
        manager->post(req,data.toUtf8());
    }else{
        manager->get(req);
    }
}

void MainWindow::RefreshBooksDisplay()
{
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->horizontalHeader()->autoScrollMargin();
    ui->tableWidget->setRowCount(books.length());
    for(int i=0;i<books.length();++i){
        ui->tableWidget->setItem(i,0,new QTableWidgetItem(books[i].id));
        ui->tableWidget->setItem(i,1,new QTableWidgetItem(books[i].name));
        ui->tableWidget->setItem(i,2,new QTableWidgetItem(books[i].author));
        ui->tableWidget->setItem(i,3,new QTableWidgetItem(books[i].time_begin));
        ui->tableWidget->setItem(i,4,new QTableWidgetItem(books[i].time_end));
        ui->tableWidget->setItem(i,5,new QTableWidgetItem(books[i].url));
    }
}

void MainWindow::on_pushButton_clicked()
{
    SendRequest("http://210.45.147.188:8080/reader/captcha.php");
}

void MainWindow::on_pushButton_2_clicked()
{
    QString data="number="+ui->lineEdit->text()+"&passwd="+ui->lineEdit_2->text()+"&captcha="+ui->lineEdit_3->text()+"&select=cert_no&returnUrl=&csrf_token="+csrf;
    SendRequest("http://210.45.147.188:8080/reader/redr_verify.php",data);
}

void MainWindow::on_tabWidget_currentChanged(int index)
{
    if(index==1)resize(1020,330);
    else if(index==0)resize(290,200);
}
